<!--
    @name 质量活动维护-新增
    @author wangjuan
-->
<template>
  <section>
    <el-dialog
      v-dialogDrag
      :title="textMap[popupsState]"
      :visible="popupsVisible"
      width="70%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="close"
      @opened="openDialog"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="filter-container filter-title">活动信息</div>
      <!-- 顶部按钮 -->
      <div class="btns-container">
        <el-button
          v-for="comp in dynamictableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}
        </el-button>
      </div>
      <div class="filter-container filter-params">
        <el-row id="elrow" ref="vailComponentList" :gutter="24">
          <component
            :is="comp.component"
            v-for="comp in tableComponents.filter((o) => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds || ''"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :is-require="comp.isRequire"
            :custom-obj="comp.customObj"
            :date-type="comp.dateType"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :options="comp.options"
            :o-fields="comp.oFields"
            @changeCode="getComponentCode"
          />
        </el-row>
      </div>

      <div class="eltabs">
        <el-tabs v-model="activeName">
          <el-tab-pane label="质量活动车辆" name="first">
            <qualityActivityCar
              ref="carTable"
              :data-for-form="dataForForm"
              :is-state="popupsState"
            />
          </el-tab-pane>
          <el-tab-pane label="工时" name="second">
            <workingHours ref="timeTable" />
          </el-tab-pane>

          <el-tab-pane label="备件" name="third">
            <sparePart ref="spartTable" />
          </el-tab-pane>

          <el-tab-pane label="其他项目" name="fourth">
            <otherProjection ref="otherTable" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import OneTableTemplate from '@/components/templates/oneTable'
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { formMixins } from '@/components/mixins/formMixins'
import api from '@/api/se/serviceActivities'

export default {
  name: 'ServiceRelesedetil',
  components: {
    OneTableTemplate,
    dialogHeader: () => import('@/components/dialogHeader'),
    qualityActivityCar: () => import('./qualityActivityCar.vue'),
    workingHours: () => import('./workingHours.vue'),
    sparePart: () => import('./sparePart.vue'),
    otherProjection: () => import('./otherProjection.vue')

  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins, formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      activeName: 'first',
      dataForForm: {},
      textMap: {
        edit: '质量活动维护',
        add: '质量活动维护'
      },
      dynamictableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.save(),
          text: '保存',
          position: 'right'
        }
      ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey10',
              labelName: '活动编码：',
              codeField: 'activityCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              validrule: {
                isformat: /^[A-Za-z0-9]+$/,
                maxlength: 20,
                resectMessage: {
                  isformat: '请输入由数字和英文字母（不区分大小写）组成的编码!'
                }
              },
              isRequire: true,
              disabled: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey11',
              labelName: '活动类别：',
              codeField: 'category',
              oFields: 'category,categoryName',
              component: () => import('@/components/org/LookupValue'),
              options: [
                { category: '1', categoryName: '召回' },
                { category: '2', categoryName: '市场质量活动' }
              ],
              type: 'dropdownList',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey12',
              labelName: '类型：',
              codeField: 'type',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'type,typeName',
              options: [
                { type: '1', typeName: '主动活动' },
                { type: '2', typeName: '被动活动' }
              ],
              type: 'dropdownList',
              isMust: true,
              disabled: false,
              span: 8
            },
            {
              compKey: 'compKey13',
              labelName: '活动主题：',
              codeField: 'theme',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey14',
              labelName: '车系：',
              codeField: 'carSeriesCode',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: api.queryCarSeries,
                selectType: '1',
                defOptionFields: ['carSeriesCode', 'carSeriesCn']
              },
              type: 'dropdownList',
              isRequire: true,
              isMust: true
            },
            {
              compKey: 'compKey15',
              labelName: '故障部位：',
              codeField: 'faultPartCode',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: api.findFaultPartName,
                selectType: '1',
                defOptionFields: ['faultPartCode', 'faultPartName']
              },
              type: 'dropdownList',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey16',
              labelName: '故障现象码：',
              codeField: 'csCtCode',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: api.findFaultPhenomenon,
                selectType: '1',
                defOptionFields: ['csCtCode', 'csCtName']
              },
              type: 'dropdownList',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey17',
              labelName: '主损件编码：',
              codeField: 'pfpCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey18',
              labelName: '通知方式：',
              codeField: 'notify',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'notify,notifyName',
              options: [
                { notify: '1', notifyName: '自然回店检修' },
                { notify: '2', notifyName: '主动邀约客户' }
              ],
              type: 'dropdownList',
              isRequire: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey19',
              labelName: '活动开始日期：',
              codeField: 'enableDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              type: 'daterange',
              isMust: true
            },
            {
              compKey: 'compKey20',
              labelName: '活动截止日期：',
              codeField: 'closeDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              type: 'daterange',
              isMust: true
            }
          ],

      formField: this.$utils.getFormField(this, {
        activityCode: '',
        category: '',
        type: '',
        theme: '',
        carSeriesCode: '',
        faultPartCode: '',
        csCtCode: '',
        pfpCode: '', // 主损件
        notify: '',
        enableDate: '',
        closeDate: '',
        carList: [],
        wiList: [],
        partList: [],
        otherList: []
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },
  watch: {
    'formField.category': {
      handler(val) {
        if (val === '1') {
          this.tableComponents[2].disabled = true
          this.formField.type = ''
        } else {
          this.tableComponents[2].disabled = false
        }
      }
    },
    'formField.activityCode': {
      handler(val) {
        if (val) {
          this.dataForForm.activityCode = val
        }
      }
    }
  },
  methods: {
    // 打开页面
    openDialog() {
      this.dataForForm = this.dynamicEditRowData // 传值到车辆选择
      if (this.popupsState === 'edit') {
        this.tableComponents[0].disabled = true
        this.dataForForm.activityCode = this.dynamicEditRowData.activityCode
        this.dataForForm.activityId = this.dynamicEditRowData.activityId
        this.$requestAPI({
          apiUrl: api.queryQualityActivityInfo.APIUrl,
          variables: {
            activityCode: this.dynamicEditRowData.activityCode,
            activityId: this.dynamicEditRowData.activityId
          }
        }).then(res => {
          if (res.result === '1') {
            this.$refs.carTable.$refs.multipleTable.list = res.rows.carList
            this.$refs.timeTable.$refs.multipleTable.list = res.rows.wiList
            this.$refs.spartTable.$refs.multipleTable.list = res.rows.partList
            this.$refs.otherTable.$refs.multipleTable.list = res.rows.otherList
          }
        })
      } else {
        this.tableComponents[0].disabled = false
        this.dataForForm.activityId = ''
        this.dataForForm.activityCode = ''
      }
    },

    // 保存
    save() {
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        if (this.popupsState === 'add') {
          this.addSave()
        } else {
          this.editSave()
        }
      }
    },
    // 新增保存
    addSave() {
      const sendDatas = { ...this.formField }
      sendDatas.carList = this.$refs.carTable.$refs.multipleTable.list
      sendDatas.wiList = this.$refs.timeTable.$refs.multipleTable.list
      sendDatas.partList = this.$refs.spartTable.$refs.multipleTable.list
      sendDatas.otherList = this.$refs.otherTable.$refs.multipleTable.list
      this.sendMethods(sendDatas, api.saveQualityActivity)
    },
    // 修改保存
    editSave() {
      const sendDatas = { ...this.formField }
      sendDatas.status = this.dynamicEditRowData.status
      sendDatas.activityId = this.dynamicEditRowData.activityId
      sendDatas.carList = this.$refs.carTable.$refs.multipleTable.list
      sendDatas.wiList = this.$refs.timeTable.$refs.multipleTable.list
      sendDatas.partList = this.$refs.spartTable.$refs.multipleTable.list
      sendDatas.otherList = this.$refs.otherTable.$refs.multipleTable.list
      this.sendMethods(sendDatas, api.saveQualityActivity)
    },
    // 方法
    sendMethods(sendDatas, sendApi) {
      const queryObj = {
        type: 'mutation',
        apiConfig: sendApi,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: sendDatas
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.close()
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    close(type) {
      this.$emit('close', type)
      this.$refs.carTable.$refs.multipleTable.list = []
      this.$refs.timeTable.$refs.multipleTable.list = []
      this.$refs.spartTable.$refs.multipleTable.list = []
      this.$refs.otherTable.$refs.multipleTable.list = []
      this.reset()
    }
  }
}
</script>

<style lang="scss" scoped>
.btns-container {
  width: 100%;
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  background-color: #fff;
  .el-button {
    float: right;
    margin-left: 10px;
  }
}
/deep/.filter-params .el-col {
  margin-bottom: 15px;
}

#elrow {
  margin-right: 0 !important;

}
</style>
